package gdonly.top.signin.business;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import gdonly.top.signin.R;
import gdonly.top.signin.entity.User;
import gdonly.top.signin.utils.DatabaseQuery;
import gdonly.top.signin.utils.SsidCreater;
import gdonly.top.signin.utils.WifiUtil;

/**
 * Created by zhuzhuxia on 2017/4/27.
 */
public class SignByMonitorActivity extends AppCompatActivity {
    private ImageView imageView;
    private Button startSignBtn, stopSignBtn,queryBtn;
    private TextView signStateTv,dateTv;
    private Spinner spinner;
    private String classId, courseName, courseId;
    private int count;
    private static final int INTERVAL = 1000;
    private static final int COUNT_DOWN = 1000 * 60 * 10;
    private String[] courseNames ;
    private String[] courseIds = {"001","002", "003", "004", "005"};

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == DatabaseQuery.TIMER_HAS_DOWN){
                Toast.makeText(SignByMonitorActivity.this, "时间已经截止～", Toast.LENGTH_SHORT).show();
                stopSign();

            }
            else{
                signStateTv.setText(msg.what +" / "+ count);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_by_monitor);
        initViews();
    }
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.sign_start_btn:
                    stopSignBtn.setVisibility(View.VISIBLE);
                    imageView.setVisibility(View.VISIBLE);
                    signStateTv.setVisibility(View.VISIBLE);
                    startSignBtn.setVisibility(View.GONE);

                    startSign();

                    break;
                case R.id.sign_stop_btn:
                    stopSign();
                    break;
                case R.id.sign_query_btn:
                    Intent intent = new Intent(SignByMonitorActivity.this,QuerySignInfoActivity.class);
                    startActivity(intent);

                    break;
            }
        }
    };

    CountDownTimer timer = new CountDownTimer(COUNT_DOWN, INTERVAL) {
        @Override
        public void onTick(long millisUntilFinished) {

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    long t = System.currentTimeMillis();
                    Date date = new Date(t);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                    dateTv.setText(sdf.format(date));
                }
            };

            runOnUiThread(runnable);
        }

        @Override
        public void onFinish() {

        }
    };




    private void startSign(){
        String ssid = SsidCreater.create();

        //post id , ssid ,mac
        User self = ((Application) getApplication()).getThisUser();
        self.setSsid(ssid);

        classId = ((Application)getApplication()).getThisUser().getClassId();

        count = DatabaseQuery.queryHeadCount(SignByMonitorActivity.this, self.getClassId());
        signStateTv.setText("1 / " + count);

        WifiUtil.getMac(SignByMonitorActivity.this);

        DatabaseQuery.uploadSelfInfo(SignByMonitorActivity.this, self);//更改班级的签到ssid
        DatabaseQuery.signEnabled(SignByMonitorActivity.this, self);//启动签到开关
        DatabaseQuery.queryActualSigned(SignByMonitorActivity.this, self.getClassId(), handler);
        WifiUtil.openApAndChangeSSID(SignByMonitorActivity.this, ssid);


    }

    private void stopSign(){


        WifiUtil.closeAp();

        DatabaseQuery.cancelQueryActual();

        User self = ((Application) getApplication()).getThisUser();
        List<User> users = DatabaseQuery.querryTruntUsers(SignByMonitorActivity.this, self.getClassId(),
                dateTv.getText().toString(), courseId);

        ((Application) getApplication()).setTruntUsers(users);//把Users存储下来

        DatabaseQuery.signDisenabled(SignByMonitorActivity.this, self);//关闭签到开关，并且清空数据


        for (User user : users) {
            Log.e("TAG", user.getName());
        }



        Intent intent = new Intent(SignByMonitorActivity.this, ShowSignResultActivity.class);


        intent.putExtra("course_name",courseName );
        intent.putExtra("date", dateTv.getText().toString().trim());
        startActivity(intent);
        finish();
    }

    private void initViews(){

        courseNames = getResources().getStringArray(R.array.courses);

        imageView = (ImageView) findViewById(R.id.wait_sign_anima);
        imageView.setImageResource(R.drawable.wait_sign_view);
        imageView.setVisibility(View.GONE);

        signStateTv = (TextView) findViewById(R.id.sign_state);
        signStateTv.setVisibility(View.GONE);

        startSignBtn = (Button) findViewById(R.id.sign_start_btn);
        startSignBtn.setOnClickListener(listener);

        stopSignBtn = (Button) findViewById(R.id.sign_stop_btn);
        stopSignBtn.setVisibility(View.GONE);
        stopSignBtn.setOnClickListener(listener);

        queryBtn = (Button) findViewById(R.id.sign_query_btn);
        queryBtn.setOnClickListener(listener);

        dateTv = (TextView) findViewById(R.id.date);
        spinner = (Spinner) findViewById(R.id.spinner);
//        courseTv = (TextView) findViewById(R.id.course_name);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                courseName = courseNames[position];
                courseId = courseIds[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                courseName = courseNames[0];
                courseId = courseIds[0];
            }
        });
        timer.start();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(imageView == null){
            imageView = (ImageView) findViewById(R.id.wait_sign_anima);
            imageView.setImageResource(R.drawable.wait_sign_view);
        }
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
        animationDrawable.start();
    }
}
